package proyecto.dao;

import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import proyecto.excepcion.DAOExcepcion;
import proyecto.modelo.Censura;

public class CensuraDAOImpl extends HibernateDaoSupport implements CensuraDAO {

	protected Log log = LogFactory.getLog(getClass());

	private DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	@SuppressWarnings("unchecked")
	public List<Censura> listar() throws DAOExcepcion {
		log.info("listar()");
		List<Censura> lista = new ArrayList<Censura>();
		try {
			lista = getHibernateTemplate().find("from Censura");
		} catch (DataAccessException e) {
			log.error(e.toString());
			throw new DAOExcepcion(e.getMessage());
		}
		return lista;
	}

	public Censura obtener(String coCensura) throws DAOExcepcion {
		log.info("obtener() : " + coCensura);
		Censura modelo = new Censura();
		try {
			modelo = (Censura) getHibernateTemplate().find(
					"from Censura a where trim(a.co_Censura) = ?",
					coCensura).get(0);
		} catch (Exception e) {
			log.error("Error: " + e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}
	
	public Censura actualizar(Censura modelo) throws DAOExcepcion {
		try {
			getHibernateTemplate().update(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}
	
	public Censura insertar(Censura modelo) throws DAOExcepcion {
		try {
			getHibernateTemplate().save(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
		return modelo;
	}
	
	public void eliminar(String coCensura) throws DAOExcepcion {
		Censura modelo = new Censura();
		modelo.setCoCensura(coCensura);
		try {
			getHibernateTemplate().delete(modelo);
			getHibernateTemplate().flush();
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		}
	}
}
